package com.itheima.app.interceptor;

import cn.hutool.core.util.StrUtil;
import com.itheima.app.manager.UserManager;
import com.itheima.domain.db.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import sun.security.ssl.SSLContextImpl;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/*
* 拦截器，需要将token转化为user
* 需要被扫描到
* */

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private UserManager userManager;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /*
        * 1、获取请求头的token
        * 2、如果没有token，则返回登入页
        * 3、如果token没有user，则返回登入页
        * 4、将user存入到ThreadLocal中，
        * 5、放行
        * */

        String token = request.getHeader("Authorization");

        if (StrUtil.isEmpty(token)){
            response.setStatus(401);
            return false;
        }

        User user = userManager.findByToken(token);

        if (user == null){
            response.setStatus(401);
            return false;
        }

        UserHolder.set(user);
        return true;
    }

    //最终处理
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.remove();
    }
}
